<?php
/**
 * 文件上传controller
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\admin\controller;

use Exception;
use support\Request;
use support\Response;
use taoser\exception\ValidateException;
use Shopwwi\WebmanFilesystem\Facade\Storage;

class FileController extends AdminBaseController
{

    /**
     * 表单上传组建使用
     * @param Request $request
     * @return Response
     */
    public function upload(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $config = config('filesystem.disks.public');

            $param = $request->all();
            $field = $param['file_field'] ?? 'file';
            // 文件类型，默认图片
            $file_type = $param['file_type'] ?? 'image';
            // 上传到本地，可自行修改为oss之类的

            $file = $request->file($field);
            //单文件判断
            try {
                $path   = $config['url'] . '/' . date('Ym') . '/' . date('d');
                $result = Storage::adapter('public')
                    ->path($path)
                    ->size($config['validate'][$file_type]['size'])
                    ->extYes($config['validate'][$file_type]['mime'])
                    ->upload($file);

                $url = '/' . str_replace("\\", '/', $result->file_name);

                return json([
                    'code'                 => 200,
                    'initialPreview'       => [$url],
                    'initialPreviewAsData' => true,
                    'showDownload'         => false,
                    'initialPreviewConfig' => [
                        [
                            'downloadUrl' => $url,
                            'key'         => $result->origin_name,
                            'caption'     => $result->origin_name,
                            'url'         => url('admin/file/del', ['file' => $url]),
                            'size'        => $file->getSize(),
                        ]
                    ],
                ]);
            } catch (Exception $e) {
                return admin_error($e->getMessage());
            }
        }

        return admin_error('非法访问');
    }

    /**
     * 编辑器上传
     * @param Request $request
     * @return Response
     */
    public function editor(Request $request): Response
    {

        if ($request->method() === 'POST') {
            $param = $request->all();
            $field = $param['file_field'] ?? 'file';
            $dir   = $param['file_dir'] ?? 'editor';
            // 文件类型，默认图片
            $file_type = $param['file_type'] ?? 'image';
            // 上传到本地，可自行修改为oss之类的
            $config = config('filesystem.disks.public');

            $file = $request->file($field);

            try {
                $path   = $config['url'] . '/editor/' . date('Ym') . '/' . date('d');
                $result = Storage::adapter('public')
                    ->path($path)
                    ->size($config['validate'][$file_type]['size'])
                    ->extYes($config['validate'][$file_type]['mime'])
                    ->upload($file);

                $url = '/' . str_replace("\\", '/', $result->file_name);

                return json([
                    'errno' => 0,
                    'data'  => [
                        [
                            'url'  => $url,
                            'href' => '',
                            'alt'  => $result->origin_name,
                            'size' => $file->getSize(),
                        ],
                    ]
                ]);

            } catch (ValidateException $e) {
                return json([
                    "errno"   => 1,
                    'message' => $e->getMessage()
                ]);
            }

        }

        return json([
            "errno"   => 1,
            'message' => '非法访问'
        ]);
    }

    /**
     * 删除文件
     * @param Request $request
     * @return Response
     */
    public function del(Request $request): Response
    {
        $file = urldecode($request->input('file'));

        $path        = public_path() . '/' . $file;
        $true_delete = config('filesystem.form_true_delete');
        $result      = !$true_delete || @unlink($path);
        return $result ? json(['message' => '成功',]) : json(['message' => '失败']);
    }

}
